﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace System.Data.Common.QueryBuilder
{
    public class DbQueryGroupBy
    {
        public enum GroupByType
        {
            NONE,
            ROLLUP,
            CUBE
        }
        public DbQuerySelect EndGroupBy;
        private List<String> GroupingObjects;
        private String HavingParam;
        public DbQueryGroupBy(DbQuerySelect parent)
        {
            this.EndGroupBy = parent;
            this.GroupingObjects = new List<String>();
        }

        public virtual DbQueryGroupBy GroupBy(GroupByType groupType, params String[] statements)
        {
            if (groupType == GroupByType.NONE)
                this.GroupBy(statements);
            else
                this.GroupingObjects.Add(String.Concat(groupType, "(", String.Join(", ", statements), ")"));
            return this;
        }

        public virtual DbQueryGroupBy GroupBy(params String[] statements)
        {
            this.GroupingObjects.AddRange(statements);
            return this;
        }

        public virtual DbQueryGroupBy Having(String having)
        {
            this.HavingParam = having;
            return this;
        }

        public override string ToString()
        {
            String having = String.IsNullOrEmpty(this.HavingParam) == false ? String.Concat(" HAVING ", this.HavingParam) : String.Empty;
            return this.GroupingObjects.Count > 0 ? String.Concat("GROUP BY ", String.Join(", ", this.GroupingObjects), having) : String.Empty;
        }
    }
}
